<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/10/22
 * Time: 16:01
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

namespace app\common\business;


use app\common\lib\Status;
use app\common\validate\Admin as ValObj;
use app\common\model\mysql\Admin as ModelObj;
use think\Exception;
use think\facade\Log;

class User extends Base
{
    /**
     * @var ValObj
     */
    protected ValObj $valObj;
    /**
     * @var ModelObj
     */
    protected ModelObj $modelObj;

    /**
     *
     */
    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    public function add(array $data = [])
    {
        $data['code'] = md5(random_bytes(32));
        $data['move_pwd'] = md5($data['move_pwd'] . $data['code']);
        $data['move_pwd_res'] = md5($data['move_pwd_res'] . $data['code']);

        $this->isValidateAdd($data, 'add_login');
        //查询用户是否存在
        try {
            $res = $this->modelObj->where('move_user', $data['move_user'])
                ->where('status', '<>', Status::mysql_delete)
                ->find();
        } catch (\Exception $e) {
            throw new Exception("操作失败");
        }
        if (!$res) {
            $result = $this->modelObj->save($data);
            if ($result) {
                return true;
            } else {
                return false;
            }
        } else {
            throw new Exception("用户名{$data['move_user']}已经存在");
        }
    }

    public function editSave(array $data = [])
    {
        $this->isValidateAdd($data, 'editSave');
        $res = $this->modelObj->saveAll([$data]);
        if ($res) {
            return true;
        } else {
            return false;
        }
    }
}
